package wechatMiniprogram

import (
	"fmt"
	"github.com/go-redis/redis/v8"
	wechat "github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/miniprogram"
	miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
	"goadmin/config"
	"goadmin/localCache"
	"goadmin/logs"
)

type WechatConfig struct {
	AppID           string `json:"app_id"`
	AppSecret       string `json:"app_secret"`
	MchID           string `json:"mch_id"`
	MchKey          string `json:"mch_key"`
	MapKey          string `json:"map_key"`
	EnvVersion      string `json:"env_version"`
	NotifyURL       string `json:"notify_url"`
	RefundNotifyURL string `json:"refund_notify_url"`
}

var (
	wxConfig WechatConfig
	WxClient *miniprogram.MiniProgram
)

// 参考文档
// https://silenceper.com/wechat/miniprogram/auth.html
func InitWechat() {
	wxConfig = WechatConfig{
		AppID:           config.Wechat.AppID,
		AppSecret:       config.Wechat.AppSecret,
		MchID:           config.Wechat.MchID,
		MchKey:          config.Wechat.MchKey,
		EnvVersion:      "release",
		NotifyURL:       "/api/order/notice",
		RefundNotifyURL: "/api/order/refund_notify",
	}
	// 初始化微信 SDK 客户端
	wc := wechat.NewWechat()
	WxClient = wc.GetMiniProgram(&miniConfig.Config{
		AppID:     config.Wechat.AppID,
		AppSecret: config.Wechat.AppSecret,
		Cache:     cache.NewMemory(),
	})
	logs.Sugar().Info("初始化小程序配置", WxClient)
	//初始化商户客户端配置
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	// 发送请求，以下载微信支付平台证书为例
	// https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay5_1.shtml
}

type PhoneReq struct {
	EncryptedData string `json:"encryptedData" binding:"required"`
	IV            string `json:"iv"            binding:"required"`
}

// 解密手机号
func DecryptPhone(openid string, IV string, EncryptedData string) (string, error) {
	// 1.取出 openid（前面登录时写入）
	sessionKey, err := localCache.RedisDb.Get(localCache.RedisCoretxt, openid).Result()
	if err == redis.Nil {
		fmt.Println("key not exist")
	} else if err != nil {
		panic(err)
	}
	fmt.Println("k1 =", sessionKey)
	// 3. 解密
	plainData, err := WxClient.GetEncryptor().Decrypt(sessionKey, EncryptedData, IV)
	if err != nil {
		fmt.Println("解密失败", err)
		return "解密失败", err
	}
	return plainData.PurePhoneNumber, nil
}
